package com.inifitness.message.processor.message;

import com.inifitness.common.event.event.MessageEvent;
import com.inifitness.common.event.expression.MessageParserContext;
import com.inifitness.message.models.Recipient;
import com.inifitness.message.service.EventTemplate;

import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * 消息处理器接口
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024-05-29 12:48
 */
public interface MessageProcessor {

  void process(MessageEvent event, EventTemplate template);

  default Recipient parseRecipient(MessageEvent event, String recipient) {
    Recipient obj = new Recipient();
    return obj;
  }

  default String parseMessage(MessageEvent event, String template) {
    StandardEvaluationContext context = new StandardEvaluationContext(event.payload());
    ///////直接使用的话会报EL1008E: Property or field 'xxx' cannot be found on object of type 'java.util.LinkedHashMap' - maybe not public or not valid?
    ///////这里通过StandardEvaluationContext#addPropertyAccessor增加一个属性访问器MapAccessor来解决
    context.addPropertyAccessor(new MapAccessor());

    ///////这里模板使用的是${xxx}，与一般的#{}不同，需要自己重新写下ParserContext
    ExpressionParser parser = new SpelExpressionParser();
    ParserContext parserContext = new MessageParserContext();
    String content = parser.parseExpression(template, parserContext).getValue(context, String.class);
    return content;
  }
}
